<?php
namespace app\passenger\controller;
use app\AdminRest;
use app\ApiRest;
use app\card\model\DefaultSetting;
use app\shop\model\IndexCardCount;
use think\App;
use app\passenger\model\Coupon as Model;
use app\passenger\model\AdminCompany;
use app\passenger\model\IndexActive;
use app\passenger\model\Log;
use think\facade\Db;


class IndexCoupon extends ApiRest
{

    protected $model;

    protected $company_model;

    protected $log_model;

    protected $active_model;

    protected $count_model;

    public function __construct(App $app) {
        parent::__construct($app);

        $this->model= new Model();

        $this->company_model = new AdminCompany();

        $this->log_model     = new Log();

        $this->active_model  = new IndexActive();

        $this->count_model   = new IndexCardCount();


        $this->model->changeStatus();
    }


    /**
     * @author chenniang
     * @DataTime: 2020-03-12 17:56
     * @功能说明:获取优惠券
     */
    public function getUserCoupon(){

        $active_model = new IndexActive();

        $input  = $this->_param;

        //核销人必须是员工
        $is_staff = Db::name('longbing_card_user_info')->where(['fans_id'=>$this->getUserId(),'is_staff'=>1])->field('id')->find();

        if(!empty($is_staff)){

            $this->errorMsg('员工不能领取');
        }

        $share_id = !empty($input['share_user'])?$input['share_user']:0;

        Db::startTrans();
        //查找活动
        $active = $active_model->where(['id'=>$input['id']])->find();

        if(empty($active)){
            $this->errorMsg('活动不存在');
        }

        $active = $active->toArray();
        //开始时间
        if($active['start_time']>time()){

            $this->errorMsg('活动未开始');

        }
        //结束时间
        if($active['end_time']<time()){

            $this->errorMsg('活动已结束');
        }

        $all_dis = [

            'type'      => 1,

            'active_id' => $active['id'],

            'uniacid'   => $this->_uniacid,
        ];
        //总的领取数
        $all_coupon_num = $this->model->where($all_dis)->count();
        //是否领取完
        if($active['user_coupon_num']<=$all_coupon_num){

            $this->errorMsg('用户券已经被领取完');

        }

        $dis = [
            'uniacid' => $this->_uniacid,

            'user_id' => $this->getUserId(),

            'active_id' => $active['id'],

            'type'    => 1
        ];
        //查找是否领取过
        $coupon = $this->model->where($dis)->find();

        if(!empty($coupon)){

            $this->errorMsg('已经领取过优惠券');
        }
        //判断是否达到分享领取上限
        if(!empty($share_id)){
            //查看是否是员工
            $is_staff = Db::name('longbing_card_user_info')->where(['fans_id'=>$share_id,'is_staff'=>1])->field('id')->find();
            //员工不判断
            if(empty($is_staff)){

                $all_dis = [

                    'type'      => 1,

                    'active_id' => $active['id'],

                    'uniacid'   => $this->_uniacid,

                    'share_user'=> $share_id
                ];
                //是否领取完
                $all_coupon_num = $this->model->where($all_dis)->count();

                if($all_coupon_num>=$active['coupon_num']){

                    $this->errorMsg('该分享领取已达上限');
                }

            }

        }
        //用户id
        $user_id  = $this->getUserId();
        //员工id
        $staff_id = $input['staff_id'];
        //过期时间类型
        if($active['user_out_type']==1){
            //指定时间
            $start = $active['user_coupon_start'];

            $end   = $active['user_coupon_end'];

        }else{
            //天数
            $start = time();

            $end   = time()+$active['user_out_day']*86400;
        }

        $data = [
            //uniacid
            'uniacid'      => $this->_uniacid,
            //用户
            'user_id'      => $user_id,
            //员工id
            'staff_id'     => $staff_id,
            //优惠券名称
            'coupon_name'  => $active['user_coupon_data'],
            //类型
            'type'         => 1,
            //分享者id
            'share_user'   => $share_id,
            //分享者的优惠券
            'share_coupon' => 0,
            //活动id
            'active_id'    => $active['id'],
            //状态
            'status'       => 1,
            //开始时间
            'start_time'   => $start,
            //结束时间
            'end_time'     => $end,
            //使用范围
            'user_range'   => $active['user_coupon_range'],
        ];


        //插入
        $res = $this->model->couponAdd($data);
        //初始化一下
        $this->log_model->initToday();

        $log_dis = [
            //员工
            'staff_id' => $staff_id,
            //活动
            'active_id'=> $active['id'],
            //用户
            'user_id'  => $share_id,
            //uniacid
            'uniacid'  => $this->_uniacid,
        ];
        //添加到日志
        $this->log_model->logInset($log_dis,'get_num');
        //上报雷达
        $inset_data = [
            //用户
            'user_id' => $this->getUserId(),
            //员工
            'to_uid'  => $staff_id,
            //类型
            'type'    => 556,
            //标签
            'sign'    => 'view',
            //id
            'target'  => $active['id'],
            //uniacid
            'uniacid' => $this->_uniacid
        ];
        //添加
        $insert_id = $this->count_model->countAdd($inset_data);
        //发送
        $push_data = array(
            'action'  => 'longbingSendWxServiceNotice',

            'event'   => 'longbingSendWxServiceNotice',

            'count_id'=> $insert_id
        );
        publisher(json_encode($push_data ,true));

        $lock = $active_model->where(['id'=>$input['id'],'update_time'=>$active['update_time']])->update(['update_time'=>$active['update_time']+1]);

        if($lock!=1){

            $this->errorMsg('领取人数过多,请重新领取');

        }

        Db::commit();

        return $this->success($res);
    }


    /**
     * @author chenniang
     * @DataTime: 2020-03-12 17:56
     * @功能说明:获取优惠券
     */
    public function hxCoupon(){

        $input  = $this->_input;
        //核销人必须是员工
        $is_staff = Db::name('longbing_card_user_info')->where(['fans_id'=>$this->getUserId(),'is_staff'=>1])->field('id')->find();

        if(empty($is_staff)){

            $this->errorMsg('只有员工才能核销');
        }
        $coupon = $this->model->couponInfo(['id'=>$input['id']]);
        //查看有资格核销的人
        $default_model = new DefaultSetting();
        //默认配置
        $default       = $default_model->settingInfo(['uniacid'=>$this->_uniacid]);
        //查看有资格核销的人
        if(!empty($default)&&$default['passenger_hx_type'] == 1){
                //如果没填
              if(empty($default['passenger_hx_user'])){

                  $this->errorMsg('只有指定员工才能核销');

              }

            $default['passenger_hx_user'] = json_decode($default['passenger_hx_user'],true);
              //如果没在指定人员里面
            if(!in_array($this->getUserId(),$default['passenger_hx_user'])){

                $this->errorMsg('只有指定员工才能核销');

            }
        }

        Db::startTrans();

        if(empty($coupon)){

            $this->errorMsg('券不存在');
        }
        //是否被核销
        if($coupon['status']==2){

            $this->errorMsg('券已核销');

        }
        //是否到了核销时间
        if($coupon['start_time']>time()){

            $this->errorMsg('券还未到核销时间,核销时间'.date('Y-m-d H:i:s',$coupon['start_time']));
        }
        //是否过期
        if($coupon['end_time']<time()){

            $this->errorMsg('券已经过期');
        }
        //核销
        $res = $this->model->couponUpdate(['id'=>$input['id'],'status'=>1],['status'=>2,'hx_user'=>$this->getUserId()]);

        if($res != 1){

            $this->errorMsg('核销失败');
        }

        $active_model = new IndexActive();
        //查找活动
        $active = $active_model->where(['id'=>$coupon['active_id']])->find();

        if(!empty($active)&&!empty($coupon['share_user'])&&$coupon['type']==1){

            $is_staff = Db::name('longbing_card_user_info')->where(['fans_id'=>$coupon['share_user'],'is_staff'=>1])->field('id')->find();
            //员工没有
            if(empty($is_staff)){

                $active   = $active->toArray();
                //员工id
                $staff_id = $coupon['staff_id'];

                if($active['out_type']==1){

                    $start = $active['coupon_start'];

                    $end   = $active['coupon_end'];

                }else{

                    $start = time();

                    $end   = time()+$active['out_day']*86400;
                }

                $data = [
                    //uniacid
                    'uniacid'      => $this->_uniacid,
                    //用户
                    'user_id'      => $coupon['share_user'],
                    //员工id
                    'staff_id'     => $staff_id,
                    //优惠券名称
                    'coupon_name'  => $active['coupon_data'],
                    //类型
                    'type'         => 2,
                    //分享者id
                    'share_user'   => 0,
                    //分享者的优惠券
                    'share_coupon' => $coupon['id'],
                    //活动id
                    'active_id'    => $active['id'],
                    //状态
                    'status'       => 1,
                    //开始时间
                    'start_time'   => $start,
                    //结束时间
                    'end_time'     => $end,
                    //使用范围
                    'user_range'   => $active['coupon_range'],
                ];

                $res = $this->model->couponAdd($data);

                $inset_data = [
                    'user_id' => $coupon['share_user'],
                    'to_uid'  => $staff_id,
                    'type'    => 561,
                    'sign'    => 'view',
                    'target'  => $coupon['active_id'],
                    'uniacid' => $this->_uniacid
                ];
                $insert_id = $this->count_model->countAdd($inset_data);

                $push_data = array(
                    'action'  => 'longbingSendWxServiceNotice',

                    'event'   => 'longbingSendWxServiceNotice',

                    'count_id'=> $insert_id
                );
                publisher(json_encode($push_data ,true));
            }

            //初始化一下
            $this->log_model->initToday();

            $log_dis = [

                'staff_id' => $coupon['staff_id'],

                'active_id'=> $active['id'],

                'user_id'  => $coupon['share_user'],

                'uniacid'  => $this->_uniacid,
            ];

            $this->log_model->logInset($log_dis,'use_num');

        }


        $type = $coupon['type']==1?559:560;

        $inset_data = [
            'user_id' => $coupon['user_id'],
            'to_uid'  => $coupon['staff_id'],
            'type'    => $type,
            'sign'    => 'view',
            'target'  => $coupon['active_id'],
            'uniacid' => $this->_uniacid
        ];
        $insert_id = $this->count_model->countAdd($inset_data);

        $push_data = array(
            'action'  => 'longbingSendWxServiceNotice',

            'event'   => 'longbingSendWxServiceNotice',

            'count_id'=> $insert_id
        );
        publisher(json_encode($push_data ,true));

        Db::commit();

        return $this->success($res);
    }


    /**
     * @author chenniang
     * @DataTime: 2020-03-24 13:57
     * @功能说明:分享增加日志
     */
    public function shareLog(){

        $input  = $this->_input;
        //初始化一下
        $this->log_model->initToday();

        $log_dis = [

            'staff_id' => $input['staff_id'],

            'active_id'=> $input['active_id'],

            'user_id'  => $this->getUserId(),

            'uniacid'  => $this->_uniacid,
        ];

        $res = $this->log_model->logInset($log_dis,'share_num');

        $res = $this->log_model->logInset($log_dis,'share_today_num');

        $inset_data = [
            'user_id' => $this->getUserId(),
            'to_uid'  => $input['staff_id'],
            'type'    => 557,
            'sign'    => 'view',
            'target'  => $input['active_id'],
            'uniacid' => $this->_uniacid
        ];
        $insert_id = $this->count_model->countAdd($inset_data);

        $push_data = array(
            'action'  => 'longbingSendWxServiceNotice',

            'event'   => 'longbingSendWxServiceNotice',

            'count_id'=> $insert_id
        );
        publisher(json_encode($push_data ,true));

        return $this->success($res);
    }


    /**
     * @author chenniang
     * @DataTime: 2020-03-16 17:56
     * @功能说明:优惠券列表
     *
     */
    public function userCouponList(){

        $input  = $this->_input;
        //uniacid
        $dis[]  = ['uniacid','=',$this->_uniacid];
        //用户id
        $dis[]  = ['user_id','=',$this->getUserId()];
        //状态
        $dis[]  = ['status','=',$input['status']];
        //类型
        $dis[]  = ['type','=',$input['type']];

        $data = $this->model->couponList($dis,10);

        return $this->success($data);
    }


    /**
     * @author chenniang
     * @DataTime: 2020-03-23 09:50
     * @功能说明:用户优惠券详情
     */
    public function userCouponInfo(){

        $input  = $this->_input;

        $dis = [

          'id' => $input['id']
        ];
        //优惠券详情
        $coupon = $this->model->couponInfo($dis);
        //为空报错
        if(empty($coupon)){
            return $this->error('券未找到');
        }
        //活动
        $active = $this->active_model->where(['id'=>$coupon['active_id']])->find();

        //为空报错
        if(empty($active)){
            return $this->error('活动未找到');
        }else{
            $active = $active->toArray();
        }
        //活动标题
        $coupon['active_title'] = $active['title'];
        //活动封面图
        $coupon['active_cover'] = $active['cover'];
        //活动客推荐人数
        $coupon['coupon_num']   = $active['coupon_num'];
        //可以领取人数
        $coupon['user_coupon_num'] = $active['user_coupon_num'];
        //邀请已经使用的记录
        $coupon['user_list']  = $this->model->getUserList($coupon);
        //被邀请已经使用的记录
        $coupon['share_list'] = $this->model->shareUserList($coupon);
        //获取优惠券码
        $coupon['qr']         = $this->model->getCouponQr($coupon,$input,$this->getUserId());

        $coupon['qr']         = !empty($coupon['qr']['qr_path'])?$coupon['qr']['qr_path']:'';
        return $this->success($coupon);
    }


    /**
     * @author chenniang
     * @DataTime: 2020-03-23 14:51
     * @功能说明:员工端的分享领取记录
     */
    public function staffShareRecord(){

        $input = $this->_param;

        $input['staff_id'] = $this->getUserId();

        if(!empty($input['status'])&&$input['status']==1){
            //推荐记录
            $data = $this->log_model->staffShareList($input['staff_id'],$input['active_id']);

        }else{
            //领取记录
            $data = $this->model->staffUserList($input['staff_id'],$input['active_id']);
        }
        return $this->success($data);
    }


    /**
     * @author chenniang
     * @DataTime: 2020-03-24 10:22
     * @功能说明:员工端用户详情
     */
    public function staffUserInfo(){

        $input = $this->_input;
        //用户详情
        $data['user_info'] = $this->log_model->staffUserInfo($input['user_id'],$input['active_id'],$this->getUserId());

        if($input['status']==2){
            //该用户端领取情况
            $dis = [
                //活动
                'active_id' => $input['active_id'],
                //用户
                'user_id'   => $input['user_id'],
                //员工
                'staff_id'  => $this->getUserId(),

            ];
            //查询
            $data['list'] = $this->model->couponList($dis,10);

        }else{
            //该用户的分享情况
            $dis = [
                //活动
                'a.active_id' => $input['active_id'],
                //推荐人
                'a.share_user'=> $input['user_id'],
                //员工
                'a.staff_id'  => $this->getUserId(),
            ];
            //查询
            $data['list'] = $this->model->userCouponList($dis);
        }

        return $this->success($data);
    }


    /**
     * @author chenniang
     * @DataTime: 2020-03-24 18:25
     * @功能说明:核销券详情
     */
    public function hxCouponInfo(){

        $input = $this->_input;

        $data  = $this->model->couponInfo(['id'=>$input['id']]);

        if(empty($data)){
            return $this->error('券未找到');
        }

        $data['user_info'] = [];

        if($data['share_user']&&$data['type']==1){

            $is_staff = Db::name('longbing_card_user_info')->where(['fans_id'=>$data['share_user'],'is_staff'=>1])->field('id')->find();

            if(empty($is_staff)){

                $data['user_info']   = Db::name('longbing_card_user')->where(['id'=>$data['share_user']])->field('avatarUrl,nickName')->find();
            }
        }
        return $this->success($data);

    }


    /**
     * User: chenniang
     * Date: 2019-09-26 10:32
     * @return void
     * descption:生成活动二维码
     */
    public function getQr(){
        $input = $this->_input;
        $qr    = getCache($this->getUserId().'-'.$input['type'].'-'.$input['staff_id'].'-'.$input['id']."-active_qr",$this->_uniacid);
        if(empty($qr)){
            $input['pid'] = $this->getUserId();
            $data = longbingCreateWxCode($this->_uniacid,$input,$input['page']);
            $data = transImagesOne($data ,['qr_path'] ,$this->_uniacid);
            $qr   = $data['qr_path'];
            setCache($this->getUserId().'-'.$input['type'].'-'.$input['staff_id'].'-'.$input['id']."-active_qr",$qr,3600,$this->_uniacid);
        }
        return $this->success($qr);
    }





}
